package xin.yangshuai.springsecurity03.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.context.SecurityContextRepository;
import xin.yangshuai.springsecurity03.textmessage.TextMessageAuthenticationFilter;
import xin.yangshuai.springsecurity03.textmessage.TextMessageAuthenticationProvider;

/**
 * TextMessageLoginConfigurer
 *
 * @author shuai
 * @date 2025/10/14
 */
@Configuration
public class TextMessageLoginConfigurer implements SecurityConfigurer<DefaultSecurityFilterChain, HttpSecurity> {

    @Autowired
    private UserDetailsManager userDetailsManager;

    @Override
    public void init(HttpSecurity http) throws Exception {

    }

    @Override
    public void configure(HttpSecurity http) throws Exception {

        TextMessageAuthenticationProvider textMessageAuthenticationProvider = new TextMessageAuthenticationProvider();
        textMessageAuthenticationProvider.setUserDetailsService(userDetailsManager);

        TextMessageAuthenticationFilter textMessageAuthenticationFilter = new TextMessageAuthenticationFilter();
        textMessageAuthenticationFilter.setAuthenticationManager((AuthenticationManager)http.getSharedObject(AuthenticationManager.class));
        textMessageAuthenticationFilter.setSecurityContextRepository((SecurityContextRepository) http.getSharedObject(SecurityContextRepository.class));
        textMessageAuthenticationFilter.setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler("/sms-login?error"));

        http.authenticationProvider(textMessageAuthenticationProvider);
        http.addFilterAfter(textMessageAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
